﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using RestSharp;
using RestSharp.Deserializers;
using RestSharp.Serializers;

namespace YmtAuth.AppService.JavaService.Utils
{
    public static class RestClientExtensions
    {
        static RestClientExtensions()
        {

        }
        public static bool IsSuccessStatusCode(this IRestResponse response)
        {
            return response.ResponseStatus == ResponseStatus.Completed && (int)response.StatusCode / 100 == 2;
        }

        public static void ThrowException(this IRestResponse response)
        {
            string message = response.ErrorMessage;
            if (string.IsNullOrWhiteSpace(message) && response.ErrorException != null)
                message = response.ErrorException.Message;
            if (!string.IsNullOrWhiteSpace(response.Content) && response.Content.StartsWith("{") &&
                response.Content.EndsWith("}"))
                message = response.Content;
            if (string.IsNullOrWhiteSpace(message) && !string.IsNullOrWhiteSpace(response.StatusDescription))
                message = string.Concat((int)response.StatusCode, ":", response.StatusDescription);
            if (string.IsNullOrWhiteSpace(message))
                message = response.Content;

            throw new WebException(message, response.ErrorException);
        }

        public static void CheckResponse(this IRestResponse response, bool throwOut = true)
        {
            if (!response.IsSuccessStatusCode())
            {
                if (throwOut)
                    response.ThrowException();
            }
        }

        public static void UseJsonDotNetSerializerWrapper(this IRestRequest request)
        {
            request.RequestFormat = DataFormat.Json;
            request.JsonSerializer = new JsonDotNetSerializerWrapper();
        }
        public static void UseJsonDotNetDeserializerWrapper(this IRestClient client)
        {
            JsonDotNetDeserializerWrapper wrapper = new JsonDotNetDeserializerWrapper();
            client.RemoveHandler("application/json");
            client.AddHandler("application/json", wrapper);
            client.RemoveHandler("text/json");
            client.AddHandler("text/json", wrapper);
            client.RemoveHandler("text/x-json");
            client.AddHandler("text/x-json", wrapper);
            client.RemoveHandler("text/javascript");
            client.AddHandler("text/javascript", wrapper);
        }
    }

    internal class JsonDotNetSerializerWrapper : ISerializer
    {
        public JsonDotNetSerializerWrapper()
        {
            this.ContentType = "application/json";
        }

        public string Serialize(object obj)
        {
            // return JsonConvert.SerializeObject(obj);
            return JsonConvert.SerializeObject(obj, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Include, DefaultValueHandling = DefaultValueHandling.Include });
        }

        public string DateFormat { get; set; }
        public string RootElement { get; set; }
        public string Namespace { get; set; }
        public string ContentType { get; set; }
    }

    internal class JsonDotNetDeserializerWrapper : IDeserializer
    {
        public T Deserialize<T>(IRestResponse response)
        {
            return JsonConvert.DeserializeObject<T>(response.Content);
        }
        public string RootElement { get; set; }
        public string Namespace { get; set; }
        public string DateFormat { get; set; }
    }
}
